<template>
  <view class="container">
    <!-- 这里必定要封装，可能一个搜索框，还有个分类框 -->
    <view class="container-box">
      <message-search></message-search>
      <!--分类框-->
      <view class="tab-box">
        <!-- type -->
        <view class="tab-item" :class="{active: activeNumber === 4   }" @tap="changeTab(4)">{{selectedText}}<uni-icons
            type="down" size="10"></uni-icons></view>
        <!-- 条件查询-->
        <view class="tab-item" :class="{active: activeNumber === ''}" @tap="changeTab('')">全部</view>
        <view class="tab-item" :class="{active: activeNumber === 1}" @tap="changeTab(1)">审批中</view>
        <view class="tab-item" :class="{active: activeNumber === 2}" @tap="changeTab(2)">审批批准</view>
        <view class="tab-item" :class="{active: activeNumber === 3}" @tap="changeTab(3)">驳回审批</view>
      </view>
    </view>
    <!-- 添加销假时的逻辑判断 -->
    <message-list :appliCationList="appliCationList" @delete="handleDelete" @edit="handleEdit"
      @view-detail="handleViewDetail"></message-list>
    <message-tab ref="showTab" @select="updateList"></message-tab>
    <!-- 添加数据为空的数据提示 -->
    <empty-state v-if="appliCationList.length===0"></empty-state>
  </view>
</template>

<script>
  import bageMix from '@/mixins/auth.js'
  import tabbar from '@/mixins/tabbar-badge.js'
  import {
    exposeFormatTime
  } from '@/utils/format.js'
  import {
    mapMutations
  } from 'vuex'
  export default {
    mixins: [bageMix, tabbar],
    data() {
      return {
        queryObj: {
          page: 1,
          pageSize: 5,
          type: '',
          approvalStatus: ''
        },
        appliCationList: [],
        Total: '', // 数据总量
        current_total: '', // 目前的获取到的数据量
        activeNumber: '',
        selectedText: '分类',
        isLoading: false
      }
    },
    onLoad() {
      uni.$on('refreshMessageList', this.handleRefreshEvent);
      if (this.$store.state.m_user.token && this.$store.state.m_user.token !== '') {
        this.applicationList()
      }
    },
    onUnload() {
      // 页面卸载时移除监听，避免内存泄漏
      uni.$off('refreshMessageList', this.handleRefreshEvent);
    },
    onReachBottom() {
      if (this.queryObj.page * this.queryObj.pageSize >= this.Total) return uni.$showMsg('数据加载完毕!!')
      if (this.isLoading) return
      this.queryObj.page += 1
      this.applicationList()
    },
    onPullDownRefresh() {
      this.handleRefresh()
    },
    methods: {
      ...mapMutations('m_mess', ['updateTotal']),
      handleRefreshEvent(payload = {
        resetPage: true
      }) {
        if (payload.resetPage) {
          this.queryObj.page = 1; // 重置为第一页
          this.appliCationList = []; // 清空旧数据
        }
        this.applicationList();
      },
      async applicationList(cb) {
        this.isLoading = true;
        try {
          const res = await uni.$http.get('/attendance/leaveRecord', this.queryObj);
          this.appliCationList = [...this.appliCationList, ...res.data.data.row];
          this.Total = res.data.data.total;
          this.updateTotal(this.Total);
        } catch (error) {
          uni.$showMsg('数据加载失败');
        } finally {
          this.isLoading = false;
          cb && cb();
        }
      },
      changeTab(num) {
        this.activeNumber = num;

        const actionMap = {
          4: () => this.$refs.showTab.showDrawer(),
          3: () => this.setApprovalStatus(3),
          2: () => this.setApprovalStatus(2),
          1: () => this.setApprovalStatus(1),
          default: () => {
            this.queryObj.approvalStatus = '';
            this.queryObj.type = '';
            this.selectedText = '分类';
            this.$refs.showTab.clearDrawerDate();
          }
        };

        (actionMap[this.activeNumber] || actionMap.default)();

        this.queryObj.page = 1;
        this.appliCationList = [];
        this.applicationList();
      },
      setApprovalStatus(status) {
        this.queryObj.approvalStatus = status;
      },
      updateList(e) {
        this.selectedText = e.text
        this.queryObj.type = e.type
        this.appliCationList = []
        this.applicationList()
      },
      handleDelete(item) {
        uni.showModal({
          title: '提示',
          content: '确认要撤销该申请吗?',
          success: async (res) => {
            if (res.confirm) {
              try {
                // 将单个id转换为字符串格式
                const ids = item.id.toString()
                await uni.$http.delete(`/attendance/deleteLeaveRecord/${ids}`)
              } catch (error) {
                uni.$showMsg('撤销失败，请重试')
                console.error('删除失败:', error)
              }
              // 删除成功后的处理,性能优化
              uni.$showMsg('撤销成功!!')
              this.appliCationList = this.appliCationList.filter(
                i => i.id !== item.id
              );
              this.Total -= 1;
              this.updateTotal(this.Total);
            }
          }
        })
      },
      handleEdit(item) {
        // 显示操作菜单
        uni.showActionSheet({
          itemList: ['修改请假原因', '延期申请', '同时修改'],
          success: (res) => {
            switch (res.tapIndex) {
              case 0:
                this.showReasonModal(item);
                break;
              case 1:
                this.showExtendModal(item);
                break;
              case 2:
                this.showCombinedModal(item);
                break;
            }
          }
        })
      },
      // 显示修改原因的弹窗
      showReasonModal(item) {
        uni.showModal({
          title: '修改请假原因',
          editable: true,
          placeholderText: '请输入新的请假原因',
          success: async (res) => {
            if (res.confirm && res.content) {
              try {
                await uni.$http.patch('/attendance/updateLeaveRecord', {
                  id: item.id,
                  reason: res.content
                });
                uni.$showMsg('修改原因成功')
                this.applicationList() // 刷新列表
              } catch (error) {
                uni.$showMsg('修改失败')
              }
            }
          }
        })
      },
      // 显示延期申请的弹窗
      showExtendModal(item) {
        const MessageList = {
          id: item.id,
          type: item.type,
          reason: item.reason,
          startTime: exposeFormatTime(item.startTime),
          endTime: exposeFormatTime(item.endTime),
          mode: 'extend'
        }
        console.log(exposeFormatTime(item.startTime))
        console.log(exposeFormatTime(item.endTime))
        uni.navigateTo({
          url: `/subpkg/form-detail/form-detail?item=${JSON.stringify(MessageList)}`
        });
      },

      // 显示同时修改的弹窗
      showCombinedModal(item) {
        uni.$showMsg('这是预留功能,仅用来测试')
      },
      handleViewDetail(item) {
        uni.navigateTo({
          url: `/pages/form-detail/form-detail?List=${JSON.stringify(item)}`
        })
        console.log(item)
      },
      handleRefresh() {
        this.queryObj.page = 1
        this.Total = ''
        this.queryObj.type = ''
        this.queryObj.approvalStatus = ''
        this.isLoading = false
        this.activeNumber = ''
        this.appliCationList = []
        this.applicationList(() => uni.stopPullDownRefresh())
      }
    }
  }
</script>

<style lang="scss">
  .container {
    background-color: #f6f6f6;
    min-height: 100vh;

    .container-box {
      background-color: #fff;
      width: 100%;
      box-shadow: 0 2rpx 24rpx rgba(0, 0, 0, 0.05);

      .tab-box {
        display: flex;
        margin-top: 20rpx;
        padding: 20rpx;

        .tab-item {
          flex: 1;
          text-align: center;
          font-size: 28rpx;
          color: #666;
          position: relative;

          &.active {
            color: #2b7ff3;
            font-weight: bold;

            &::after {
              content: '';
              position: absolute;
              bottom: -10rpx;
              left: 50%;
              transform: translateX(-50%);
              width: 40rpx;
              height: 4rpx;
              background-color: #2b7ff3;
            }
          }
        }
      }
    }
  }
</style>